<?php
// +----------------------------------------------------------------------
// | 在我们年轻的城市里，没有不可能的事！
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://utils All rights reserved.
// +----------------------------------------------------------------------
// | Author : Jansen <6206574@qq.com>
// +----------------------------------------------------------------------
namespace jansen\utils\translate;
use jansen\utils\translate\exception\TranslateException;
class Translate{
    private $handler;
    /**
     * Translate constructor.
     *
     * @param string $driver 驱动名称
     * @param array  $config 特定驱动的配置
     */
    public function __construct(string $driver, array $config=[]){
        $this->setDriver($driver, $config);
    }
    /**
     * 切换翻译引擎
     * @param string $driver 驱动名称
     * @param array  $config 特定驱动的配置
     * @author:Jansen <6206574@qq.com>
     */
    public function setDriver(string $driver, array $config=[]){
        $class = 'jansen\\utils\\translate\\drivers\\'.ucfirst(strtolower($driver));
        $this->handler = new $class($config);
    }
    /**
     * 动态调用方法
     * @param $method
     * @param $args
     * @return mixed
     * @throws \Exception
     * @author:Jansen <6206574@qq.com>
     */
    public function __call($method, $args){
        if(method_exists($this->handler, $method)){
            return call_user_func_array([$this->handler, $method], $args);
        }else{
            throw new \Exception('调用了未知方法，请检查。', E_USER_ERROR);
        }
    }
    /**
     *
     * 文本翻译
     * @param string $content   待翻译文本
     * @param string $target    目标语言
     * @param string $source    源语言
     * @return array
     * @author:Jansen <6206574@qq.com>
     */
    public function text(string $content, string $target, string $source='auto'){
        try{
            $result = call_user_func_array([$this->handler, 'text'], ['content' => $content, 'target' => $target, 'source' => $source]);
            return ['status'=>200, 'message'=>$result];
        }catch(TranslateException $e){
            return ['status'=>500, 'message'=>$e->getErrorMessage()];
        }
    }
}